import 'dart:async';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:provide/provide.dart';
import 'package:study_flutter/router/NavigatorUtils.dart';
import 'package:study_flutter/yzhg/dartTools/YEventBusUtil.dart';
import 'package:study_flutter/yzhg/module/MConstant.dart';
import 'package:study_flutter/yzhg/project/shop/content/Content.dart';
import 'package:study_flutter/yzhg/project/shop/event/YEventBusBean.dart';
import 'package:study_flutter/yzhg/project/shop/model/CateGoodsBean.dart';
import 'package:study_flutter/yzhg/project/shop/provide/CategoryGoodsList.dart';
import 'package:study_flutter/yzhg/project/shop/tools/scroll_to_index.dart';
import 'package:study_flutter/yzhg/routespath/RoutesPath.dart';

import '../../../../YConstant.dart';
import 'CategoryEventBean.dart';

//https://blog.csdn.net/gpf1320253667/article/details/104856537
class YCateGoodsList extends StatefulWidget {
  @override
  _YCateGoodsListState createState() => _YCateGoodsListState();
}

class _YCateGoodsListState extends State<YCateGoodsList> {
  //刷新控件
  EasyRefreshController _controller = EasyRefreshController();

  //ListView的控制器
  AutoScrollController controller;
  final scrollDirection = Axis.vertical;
  StreamSubscription<YEventBusBean> _event;

  @override
  void initState() {
    super.initState();

    //将ListView滚到指定位置
    controller = AutoScrollController(
        viewportBoundaryGetter: () =>
            Rect.fromLTRB(0, 0, 0, MediaQuery.of(context).padding.bottom),
        axis: scrollDirection);

    _event = YEventBusUtil.getInstance().on<YEventBusBean>().listen((data) {
      if (data.eventPosition == Content.EVENT_CATEGORY_TITLE) {
        _controller.resetLoadState();
      }

      //更新页面刷新状态
      if (data.eventPosition == Content.EVENT_REFRESH_GOODS_REFRESH) {
        if (data.eventBool) {
          _scrollToIndex();
          _controller.finishRefresh(success: true);
        } else {
          _controller.finishLoad(success: true);
        }
      } else if (data.eventPosition == Content.EVENT_GOODS_REFRESH_MORE_EMPTY) {
        //没有更多数据
        _controller.finishLoad(success: true, noMore: true);
      } else if (data.eventPosition == Content.EVENT_GOODS_REFRESH_EMPTY) {
        _controller.finishRefresh(success: true, noMore: true);
      }
    });
  }

  _scrollToIndex() async {
    await controller.scrollToIndex(0, preferPosition: AutoScrollPosition.begin);
    controller.highlight(0);
  }

  @override
  Widget build(BuildContext buildContext) {
    return Provide<CategoryGoodsListProvide>(
        builder: (context, child, goodsProvide) {
      if (goodsProvide.goodsList.length > 0) {
        return Expanded(
            child: Container(
          width: ScreenUtil().setWidth(570),
          child: EasyRefresh(
            header: MaterialHeader(),
            footer: ClassicalFooter(
              bgColor: Colors.white,
              textColor: Colors.black,
              infoColor: Colors.black,
              noMoreText: "没有更多数据",
              loadFailedText: "数据加载失败",
              loadingText: "正在加载中....",
              loadText: "上拉加载更多",
            ),
            onRefresh: () async {
              //重置上拉加载
              _controller.resetLoadState();
              //将页码进行初始化
              YEventBusUtil.getInstance().fire(CategoryEventBean(
                  goodsProvide.categoryId,
                  goodsProvide.categorySubId,
                  true,
                  1));
            },
            controller: _controller,
            child: ListView.builder(
                scrollDirection: scrollDirection,
                controller: controller,
                itemCount: goodsProvide.goodsList.length,
                itemBuilder: (context, index) {
                  return AutoScrollTag(
                      key: ValueKey(index),
                      controller: controller,
                      index: index,
                      child: _listItemWidget(
                          buildContext, goodsProvide.goodsList[index]));
                }),
            onLoad: () async {
              //重置刷新
              _controller.resetRefreshState();
              YEventBusUtil.getInstance().fire(CategoryEventBean(
                  goodsProvide.categoryId,
                  goodsProvide.categorySubId,
                  false,
                  ++goodsProvide.page));
              //累加页码
            },
          ),
        ));
      } else {
        return Container(
          margin: EdgeInsets.only(top: 40.0),
          child: Text(
            "暂无数据",
            style: TextStyle(
                fontSize: ScreenUtil().setSp(28.0), color: Colors.black),
          ),
        );
      }
    });
  }

  /*组件组合*/
  Widget _listItemWidget(BuildContext context, CateGoodsListBean goodsList) {
    return InkWell(
      onTap: () {
        //点击商品跳转到商品详情页面
        NavigatorUtils.push(
            context, '${RoutesPath.goodsDetail}?goodsId=${goodsList.goodsId}');
      },
      child: Container(
        //增加边距
        padding: EdgeInsets.only(top: 5.0, bottom: 5.0),
        decoration: BoxDecoration(
            color: Colors.white,
            border:
                Border(bottom: BorderSide(width: 1.0, color: Colors.black12))),
        child: Row(
          children: <Widget>[
            _goodsImage(goodsList),
            Column(
              children: <Widget>[_goodsName(goodsList), _goodsPrice(goodsList)],
            )
          ],
        ),
      ),
    );
  }

  //商品图片
  Widget _goodsImage(CateGoodsListBean goodsList) {
    return Container(
      width: ScreenUtil().setWidth(200),
      child: Image.network(goodsList.image),
    );
  }

  /*商品名称*/
  Widget _goodsName(CateGoodsListBean goodsList) {
    return Container(
      padding: EdgeInsets.only(left: 10.0, top: 5.0, right: 5.0, bottom: 5.0),
      width: ScreenUtil().setWidth(370),
      child: Text(
        goodsList.goodsName,
        //设置最大行数2行
        maxLines: 2,
        //超过两行显示...
        overflow: TextOverflow.ellipsis,
        style: TextStyle(fontSize: ScreenUtil().setSp(28)),
      ),
    );
  }

  //设置商品价格
  Widget _goodsPrice(CateGoodsListBean goodsList) {
    return Container(
      padding: EdgeInsets.only(left: 10.0, top: 20.0, right: 5.0, bottom: 5.0),
      width: ScreenUtil().setWidth(370),
      child: Row(
        children: <Widget>[
          Text(
            "价格:¥ ${goodsList.presentPrice}",
            style:
                TextStyle(color: Colors.pink, fontSize: ScreenUtil().setSp(30)),
          ),
          Text(
            "¥${goodsList.oriPrice}",
            style: TextStyle(
                color: Colors.black12,
                fontSize: ScreenUtil().setSp(24),
                decoration: TextDecoration.lineThrough),
          )
        ],
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    _event.cancel();
  }
}
